package com.star.system.filter;

import com.star.system.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/*
			  ________   ___   ___        ___   ________   ___   ___        ___
	 ________|\   __  \_|\  \_|\  \______|\  \_|\   __  \_|\  \_|\  \______|\  \_________
	 \       \ \  \_\ /_\ \  \\ \  \     \ \  \\ \  \_\ /_\ \  \\ \  \     \ \  \        \
	  \       \ \   __  \\ \  \\ \  \     \ \  \\ \   __  \\ \  \\ \  \     \ \  \        \
	   \       \ \  \_\  \\ \  \\ \  \____ \ \  \\ \  \_\  \\ \  \\ \  \____ \ \  \        \
	    \       \ \_______\\ \__\\ \_______\\ \__\\ \_______\\ \__\\ \_______\\ \__\        \
	     \       \|_______| \|__| \|_______| \|__| \|_______| \|__| \|_______| \|__|         \
	 	  \___________________________________________________________________________________\

*/
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2.获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //3.判断访问资源是否为登录，是登录就放行
        if(request.getURI().getPath().contains("/admin/login")){
            //放行
            return chain.filter(exchange);
        }
        //4.获取所有请求头信息
        HttpHeaders headers = request.getHeaders();
        //5.获取令牌
        String jwt = headers.getFirst("token");
        //6.判断令牌是否存在，不存在返回错误信息
        if (StringUtils.isEmpty(jwt)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //拒绝访问
            return response.setComplete();
        }
        //6.1.令牌存在，校验令牌合法性，不合法返回错误信息
        try {
            JwtUtil.parseJWT(jwt);
        } catch (Exception e) {
//            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //6.2.合法放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
